package juc.producerandconsumer;

import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Buffer {
    private Lock lock;
    private Condition notFull;
    private Condition notEmpty;
    private LinkedList<Date> product;
    private int maxSize;

    Buffer(int maxSize) {
        this.maxSize = maxSize;
        lock = new ReentrantLock();
        notFull = lock.newCondition();
        notEmpty = lock.newCondition();
        product = new LinkedList<>();
    }

    public void put() {
        lock.lock();
        try {
            // 缓冲池满，阻塞生产队列
            while (product.size() > maxSize - 1 ) {
                System.out.println(Thread.currentThread().getName() + "wait");
                notFull.await();
            }
            System.out.println(Thread.currentThread().getName() + "生产产品");
            product.add(new Date());
            System.out.println("池中产品数量：" + product.size());
            Thread.sleep(1000);
            // 唤醒消费者线程
            notEmpty.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void get() {
        lock.lock();
        try {
            while (product.size() < 1) {
                // 缓冲池为空，阻塞消费者线程
                System.out.println(Thread.currentThread().getName() + "wait");
                notEmpty.await();
            }
            Date date = product.poll();
            System.out.println(Thread.currentThread().getName() + "消费" + date);
            System.out.println("池中产品数量：" + product.size());
            Thread.sleep(1000);
            // 唤醒生产者线程
            notFull.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
        	lock.unlock();
        }
    }
}
